import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, Input, Select, message } from 'antd';
import { addCustomAttribute, editCustomAttribute } from '@api/customAttribute';
import { CUSTOM_NAME_RE } from '@util/constants';
import _ from 'lodash';
import './index.less';

const prefixCls = 'site-attribute-modal';
const { Option } = Select;

class SiteAttributeModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      type: 'single',
      options: '',
      isEdit: false,
      nameError: '',
      optionsError: '',
      id: ''
    };
  }

  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(props) {
    if (props.visible) {
      let { name = '', type = 'single', options = '', _id: id = '' } = props.data;
      const isEdit = Boolean(name);
      if (options) {
        options = options.join(',');
      }
      this.setState({ name, type, isEdit, options, id });
    }
  }

  checkName = () => {
    const { name } = this.state;
    let nameError = '';
    if (name.length > 8) {
      nameError = '您输入的内容超过8个字符限制';
    }
    if (!CUSTOM_NAME_RE.test(name)) {
      nameError = '您输入的格式有误，仅支持中文、英文或短横线';
    }
    if (!name) {
      nameError = '名称不能为空';
    }
    this.setState({ nameError });
    return nameError;
  };

  checkOptions = () => {
    const { options, type } = this.state;
    let optionsError = '';
    if (!options && type !== 'string') {
      optionsError = '选项不能为空';
    }
    this.setState({ optionsError });
    return optionsError;
  };

  onNameChange = e => {
    this.setState({ name: e.target.value }, this.checkName);
  };

  onTypeChange = value => {
    let { options } = this.state;
    if (value === 'string') {
      options = '';
    }
    this.setState({ type: value, options });
  };

  onOptionsChange = e => {
    this.setState({ options: e.target.value }, this.checkOptions);
  };

  onSubmit = () => {
    const { onClose, loadList } = this.props;
    let { name, type, options, isEdit, id } = this.state;
    const todo = isEdit ? editCustomAttribute : addCustomAttribute;
    const msg = isEdit ? '编辑' : '添加';
    if ([this.checkName(), this.checkOptions()].some(i => i)) {
      return;
    }
    const body = { name, type };
    if (type !== 'string') {
      options = _.compact(_.uniq(options.replace(/[,，]/g, ',').split(',')));
      body['options'] = options;
    }
    if (id) {
      body['id'] = id;
    }
    todo(body)
      .then(() => {
        loadList();
        onClose();
        message.success(msg + '成功');
      })
      .catch(res => {
        let errMsg = _.get(res, 'message', '');
        errMsg = errMsg ? '该属性已存在' : msg + '成功';
        message.error(errMsg);
      });
  };

  render() {
    const { visible, onClose } = this.props;
    const { isEdit, name, nameError, type, options, optionsError } = this.state;
    return (
      <Modal
        maskClosable={false}
        title={isEdit ? '编辑属性' : '添加属性'}
        visible={visible}
        className={prefixCls}
        onOk={this.onSubmit}
        onCancel={onClose}
        okButtonProps={{ className: 'button-forwards' }}
      >
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>属性名称</div>
          <div className={`${prefixCls}-item-content`}>
            <Input
              placeholder="请输入数字、中文、英文或短横线，不超过8个字符"
              value={name}
              onChange={this.onNameChange}
            />
            {nameError && <span className={`${prefixCls}-item-error`}>{nameError}</span>}
          </div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>类型</div>
          <div className={`${prefixCls}-item-content`}>
            <Select value={type} style={{ width: '100%' }} onChange={this.onTypeChange}>
              <Option value="single">单选</Option>
              <Option value="multiple">多选</Option>
              <Option value="string">填空</Option>
            </Select>
          </div>
        </div>
        {type !== 'string' && (
          <div className={`${prefixCls}-item`}>
            <div className={`${prefixCls}-item-title`}>选项</div>
            <div className={`${prefixCls}-item-content`}>
              <Input
                placeholder="请输入选项名称，以逗号分隔"
                value={options}
                onChange={this.onOptionsChange}
              />
              {optionsError && <span className={`${prefixCls}-item-error`}>{optionsError}</span>}
            </div>
          </div>
        )}
      </Modal>
    );
  }
}

SiteAttributeModal.propTypes = {
  onClose: PropTypes.func,
  loadList: PropTypes.func,
  visible: PropTypes.bool,
  data: PropTypes.object
};

export default SiteAttributeModal;
